package com.fsmv.canwild;

import android.net.Uri;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.util.Log;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		if(intent.hasExtra("uri")){
			Ringtone tone = RingtoneManager.getRingtone(context, Uri.parse((String) intent.getExtras().get("uri")));
			long waitUntil = System.currentTimeMillis();
			
			if(intent.hasExtra("length")){
				waitUntil += intent.getExtras().getInt("length")*1000;
				Log.d("alarm", "length=" + intent.getExtras().getInt("length"));
			}else
				waitUntil += 3*1000;
			
			if(tone != null){
				tone.setStreamType(AudioManager.STREAM_ALARM);
				Log.d("alarm", "play");
				while(System.currentTimeMillis() <= waitUntil){
					tone.play();
				}
				tone.stop();
				Log.d("alarm", "stop");
			}
		}else{
			Toast.makeText(context, "ERROR: Select a ringtone", Toast.LENGTH_LONG).show();
		}
	}
}